import { defineStore } from "pinia"
import { ref, computed } from "vue"
import { checkGameVisible } from "@/api/api"

export type TabBarItem = {
    pagePath: string
    text: string
    iconPath: string
    selectedIconPath: string
}

export const useTabBarStore = defineStore("tabBar", () => {
    // 是否显示概率游戏tab
    const showGame = ref(false)
    // 当前激活的tab索引
    const activeIndex = ref(0)
    // 是否正在加载配置
    const loading = ref(false)

    // 所有可能的tab配置（按新顺序：概率游戏、书架、知乎壁纸、下载）
    const allTabs: TabBarItem[] = [
        {
            pagePath: "/pages/game",
            text: "概率游戏",
            iconPath: "/static/images/tabBar/ic_nav_tweet_normal.png",
            selectedIconPath: "/static/images/tabBar/ic_nav_tweet_actived.png",
        },
        {
            pagePath: "/pages/books",
            text: "书架",
            iconPath: "/static/images/tabBar/ic_nav_news_normal.png",
            selectedIconPath: "/static/images/tabBar/ic_nav_news_actived.png",
        },
        {
            pagePath: "/pages/wallpaper",
            text: "知乎壁纸",
            iconPath: "/static/images/tabBar/ic_nav_discover_normal.png",
            selectedIconPath: "/static/images/tabBar/ic_nav_discover_actived.png",
        },
        {
            pagePath: "/pages/download",
            text: "下载",
            iconPath: "/static/images/tabBar/ic_nav_my_normal.png",
            selectedIconPath: "/static/images/tabBar/ic_nav_my_actived.png",
        },
    ]

    // 根据showGame状态动态计算显示的tabs
    const visibleTabs = computed(() => {
        if (showGame.value) {
            // 显示所有4个tab
            return allTabs
        } else {
            // 不显示概率游戏，只显示后3个
            return allTabs.slice(1)
        }
    })

    // 初始化tabBar配置（从服务器获取是否显示概率游戏）
    async function initTabBarConfig() {
        if (loading.value) return
        
        loading.value = true
        try {
            const visible = await checkGameVisible()
            showGame.value = visible
            console.log("TabBar配置加载成功，显示概率游戏:", visible)
        } catch (error) {
            console.error("TabBar配置加载失败:", error)
            showGame.value = false
        } finally {
            loading.value = false
        }
    }

    // 设置当前激活的tab
    function setActiveIndex(index: number) {
        activeIndex.value = index
    }

    // 根据页面路径获取tab索引
    function getIndexByPath(path: string): number {
        return visibleTabs.value.findIndex(tab => tab.pagePath === path)
    }

    return {
        showGame,
        activeIndex,
        loading,
        visibleTabs,
        initTabBarConfig,
        setActiveIndex,
        getIndexByPath,
    }
})

